package main

import (
	"beluga/models"
	_ "beluga/models"
	_ "beluga/routers"
	"fmt"
	"time"

	"github.com/astaxie/beego/context"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

//Cfg 读取配置
var Cfg = beego.AppConfig

func init() {
	dbUser := Cfg.String("DBUser")
	dbPass := Cfg.String("DBPasswd")
	dbHost := Cfg.String("DBHost")
	dbPort := Cfg.String("DBPort")
	dbName := Cfg.String("DBName")
	maxIdleConn, _ := Cfg.Int("DBIdleConn")
	maxOpenConn, _ := Cfg.Int("DBOpenConn")
	dbLink := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbUser, dbPass, dbHost, dbPort, dbName) + "&loc=Asia%2FShanghai"
	fmt.Printf(dbLink)
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", dbLink, maxIdleConn, maxOpenConn)
}

//FilterUser 验证用户登陆状态
var FilterUser = func(ctx *context.Context) {
	cookie := ctx.GetCookie("beluga")
	o := orm.NewOrm()
	QuerySession := models.Session{Value: cookie}
	err := o.Read(&QuerySession, "Value")
	var status int
	if cookie == "" {
		status = 1
	}
	if err == orm.ErrNoRows {
		status = 2
	} else if err == orm.ErrMissPK {
		status = 3
	} else {
		if time.Now().After(QuerySession.Expire) == true {
			status = 4
			o.Delete(&QuerySession)
		} else {
			status = 0
		}
	}
	if status != 0 {
		ctx.Redirect(302, "/auth/login")
	}
}

func main() {
	orm.Debug = true
	orm.RunSyncdb("default", false, true)
	beego.InsertFilter("/cmdb/*", beego.BeforeExec, FilterUser)
	beego.Run()
}
